<?php
/**
 * Created by PhpStorm.
 * User: yafex
 * Date: 2020/8/1
 * Time: 14:58
 */

class ctrl_wish_task extends L {

    /**
     * 描述 : 构造方法
     * 作者 : Zoro.Zhu
     */
    public function __construct() {
        set_time_limit(0);
    }

    /**
     * 描述 : 抓取店小秘的订单
     * 作者 : Zoro.Zhu
     */
    public static function getDxmOrder(){
        $account = L::sql("SELECT
            account, cookie 
        FROM
            vs_account_cookie 
        WHERE
            1 ");
        foreach ($account as $acc) {
            $allOrderList = [];
            $pullOk = true;
            $pageNo = 1;
            while ($pullOk){
                $orderList = serv_rep_dxm::getOrderList($acc['cookie'], $pageNo);
                $pageNo ++;
                sleep(5);
                if(empty($orderList)){  //没有订单，跳过
                    $pullOk = false;
                }
                foreach ($orderList as $row){
                    if(isset($allOrderList[$row['orderId']])){
                        $pullOk = false;
                    }
                    $allOrderList[$row['orderId']] = $row;
                }
                unset($orderList);
            }
            if(!empty($allOrderList)){
                //开始写入数据库
                $sql = "INSERT INTO `dxm_order`(`orderId`, `orderState`, `dxmAccount`, `pullTime`, `updTime`, `orderData`, `wishUData`, `aliData`, `profitsData`,`trackData`) VALUES ";
                foreach ($allOrderList as $orderId => $orderInfo) {
                    $orderData = addslashes(json_encode($orderInfo, JSON_UNESCAPED_UNICODE));
                    $sql .= " ('{$orderId}', '{$orderInfo['orderState']}', '{$acc['account']}', '" . date('Y-m-d H:i:s') . "', '" . date('Y-m-d H:i:s') . "', '{$orderData}', '[]', '[]', '[]', '[]'),";
                    of_base_com_mq::set(['dxmGetOrderDetail', $orderId, 60], $orderInfo);
                }
                $sql = trim($sql, ',') . " ON DUPLICATE KEY UPDATE 
                `orderState` = VALUES(`orderState`),
                `updTime` = VALUES(`updTime`)";
                L::sql($sql);
            }
            unset($allOrderList);
            unset($acc);
        }

        //作废疑似合并前的订单,近一个月的订单，三小时内没有更新
        L::sql("UPDATE `dxm_order` 
	    SET `orderState` = '已作废' 
        WHERE
            orderData ->> '$.paymentTime' > '" . date('Y-m-d', time() - 86400 * 30) . "' 
        AND updTime < '" . date('Y-m-d H:i:s', time() - 3600 * 24) . "'");
        echo 'ok';
    }
    /**
     * 描述 : 抓取店小秘的退款的订单
     * 作者 : Zoro.Zhu
     */
    public static function getDxmRefundOrder(){
        $account = L::sql("SELECT
            account, cookie 
        FROM
            vs_account_cookie 
        WHERE
            1 ");
        $date = date('Y-m-d H:i:s');
        foreach ($account as $acc) {
            $orderList = serv_rep_dxm::getRefundOrderList($acc['cookie']);
            if(!empty($orderList)){
                //开始写入数据库
                $sql = "INSERT INTO `dxm_order`(`orderId`, `orderState`, `refund`, `updTime`) VALUES ";
                foreach ($orderList as $orderInfo) {
                    $refund = addslashes(json_encode($orderInfo['refund'], JSON_UNESCAPED_UNICODE));
                    $sql .= " ('{$orderInfo['orderId']}', '已退款', '{$refund}', '{$date}'),";
                    of_base_com_mq::set(['calProfits', $orderInfo['orderId'], 60], ['orderId' => $orderInfo['orderId']]);
                }
                $sql = trim($sql, ',') . " ON DUPLICATE KEY UPDATE 
                `orderState` = VALUES(`orderState`),
                `refund` = VALUES(`refund`),
                `updTime` = VALUES(`updTime`)";
                L::sql($sql);
            }
            unset($orderList);
            unset($acc);
        }
    }

    /**
     * 描述 : 获取wish邮的账单
     * 作者 : Zoro.Zhu
     */
    public static function getWishUData(){
        $account = L::sql("SELECT
            a.account,a.accessToken,b.account as dxmAccount 
        FROM
            `vs_account` a JOIN vs_account_cookie b on a.addName = b.addName
        WHERE
            type = 'wishU' 
        AND state = '0'");
        foreach($account as $row){
            $i = 1;
            while($i != 0){
                $limit = ($i - 1) * 100;
                $orderInfo = L::sql("SELECT
                    orderId,
                    orderData ->> '$.trackNo' AS trackNo 
                FROM
                    `dxm_order` 
                WHERE
                    orderState = '已发货' 
                AND dxmAccount = '{$row['dxmAccount']}' 
                ORDER BY pullTime DESC 
                LIMIT {$limit},100");
                if(!empty($orderInfo)){
                    $i++;
                    $trackNo = $trackOrderId = [];
                    foreach($orderInfo as $r){
                        $trackNo[] = $r['trackNo'];
                        $trackOrderId[$r['trackNo']] = $r['orderId'];
                    }
                    $response = serv_rapi_wishU::getOrderPayment($row['accessToken'],$trackNo);
                    $sql = "INSERT INTO `dxm_order`(`orderId`, `wishUData`) VALUES ";
                    foreach($response as $t => $logistics){
                        $json = addslashes(json_encode($logistics, JSON_UNESCAPED_UNICODE));
                        $sql .= " ('{$trackOrderId[$t]}', '{$json}'),";
                        of_base_com_mq::set(['calProfits', $trackOrderId[$t], 60], ['orderId' => $trackOrderId[$t]]);
                    }
                    $sql = trim($sql, ',') . " ON DUPLICATE KEY UPDATE 
                    `wishUData` = VALUES(`wishUData`)";
                    L::sql($sql);
                } else {
                    $i = 0;
                }
            }
        }
        echo 'ok';
    }

    /**
     * 描述 : 获取ali的订单
     * 作者 : Zoro.Zhu
     */
    public static function getAliOrder(){
        $sql = "SELECT
            orderId, orderData ->> '$.pickingRemark' as aliOrderId, dxmAccount
        FROM
            `dxm_order` 
        WHERE
            orderData ->> '$.pickingRemark' != '' 
        AND singleExpress = ''
        AND pullTime >= '" . date('Y-m-d', time() - 30 * 86400) . "'";
        $orderInfo = L::sql($sql);
        foreach ($orderInfo as $row) {
            $account = L::sql("SELECT
                a.account AS dxmAccount, b.account, b.appKey,
                b.accessToken, b.appSecret, b.refreshToken 
            FROM
                vs_account_cookie a
                LEFT JOIN vs_account b ON a.addName = b.addName 
            WHERE
                b.type = 'ali' 
            AND a.account = '{$row['dxmAccount']}'
            AND b.`state` = '0'");
            if(empty($account)){
                continue;
            }
            //每个可能采购的账号都遍历一遍，直到找到订单为止
            foreach ($account as $acc) {
                $data['aliPay'] = $acc;
                $data['buyOrder'] = $row['aliOrderId'];
                $aliInfo = model_api_aliApi::getOrderInfo($data);
                if(!empty($aliInfo)){
                    $aliData = addslashes(json_encode($aliInfo, JSON_UNESCAPED_UNICODE));
                    $costPriceTotal = $aliInfo['baseInfo']['totalAmount'];
                    $singleExpress = isset($aliInfo['nativeLogistics']['logisticsItems'][0]['logisticsBillNo']) ? $aliInfo['nativeLogistics']['logisticsItems'][0]['logisticsBillNo'] : '';
                    L::sql("UPDATE `dxm_order` 
                    SET `aliData` = '{$aliData}',
                    `costPriceTotal` = '{$costPriceTotal}',
                    `singleExpress` = '{$singleExpress}'
                    WHERE
                        `orderId` = '{$row['orderId']}'");
                    continue;
                }
            }
        }
        echo 'ok';
    }

    /**
     * 描述 : 获取店小秘渠道列表
     * 作者 : Zoro.Zhu
     */
    public static function getLogisticsList(){
        $account = L::sql("SELECT
            account, cookie 
        FROM
            vs_account_cookie 
        WHERE
            1 ");
        foreach ($account as $acc) {
            $list = serv_rep_dxm::getLogisticsList($acc['cookie']);
            $list = addslashes($list);
            L::sql("INSERT INTO `dxm_logistics`(
              `dxmAccount`, `logisticsList`, `updTime`
            ) VALUES (
              '{$acc['account']}', '{$list}', '" . date('Y-m-d H:i:s') . "'
            ) ON DUPLICATE KEY UPDATE 
                `logisticsList` = VALUES(`logisticsList`),
                `updTime` = VALUES(`updTime`)");
        }
        echo 'ok';
    }

    /**
     * 描述 : 更新wishU的访问令牌
     * 作者 : Zoro.Zhu
     */
    public static function updateWishUToken(){
//        $date = date('Y-m-d', time() - 86400);
        $sql = "SELECT
            account, appKey, appSecret, accessToken, refreshToken, addName,`type`
        FROM
            `vs_account` 
        WHERE
            `type` = 'wishU' 
        AND `state` = 0";
        if($data = L::sql($sql)){
            foreach ($data as $row) {
                $token = serv_rapi_wishU::refreshToken($row);
                if(!empty($token)){
                    $data = [
                        'account' => $row['account'],
                        'appKey' => $row['appKey'],
                        'appSecret' => $row['appSecret'],
                        'accessToken' => $token['access_token'],
                        'refreshToken' => $token['refresh_token'],
                        'invalidDate' => date('Y-m-d H:i:s', $token['expiry_time']),
                        'type' => $row['type'],
                        'data' => $token
                    ];
                    core_base::trans(null);                                                     //开启事务
                    core_account::setAccount($data);
                    core_base::trans(true);                                              //提交事务
                }
            }
        }
    }

    /**
     * 描述 : 更新wish的访问令牌
     * 作者 : Zoro.Zhu
     */
    public static function updateWishToken(){
        $date = date('Y-m-d', time() - 86400);
        $sql = "SELECT
            account, appKey, appSecret, accessToken, refreshToken, addName,`type`
        FROM
            `vs_account` 
        WHERE
            `type` = 'wish'
        and invalidDate >= '{$date}' 
        AND `state` = 0";
        if($data = L::sql($sql)){
            foreach ($data as $row) {
                $token = serv_rapi_wish::refreshToken($row);
                if(!empty($token)){
                    $data = [
                        'account' => $row['account'],
                        'appKey' => $row['appKey'],
                        'appSecret' => $row['appSecret'],
                        'accessToken' => $token['data']['access_token'],
                        'refreshToken' => $token['data']['refresh_token'],
                        'invalidDate' => date('Y-m-d H:i:s', strtotime($token['data']['expiry_time'])),
                        'type' => $row['type'],
                        'data' => $token['data']
                    ];
                    core_base::trans(null);                                                     //开启事务
                    core_account::setAccount($data);
                    core_base::trans(true);                                              //提交事务
                }
            }
        }
    }

    /**
     * 描述 : 获取正在运行的PB广告，并电话提醒
     * 作者 : Zoro.Zhu
     */
    public static function getYunPb() {
        $account = L::sql("SELECT
            account, cookie, phone
        FROM
            vs_account_cookie 
        WHERE
            closePbAds = '1' ");
        foreach ($account as $acc) {
            core_base::log(['account' => $acc['account'], 'info' => '开始'], 'getYunPb');
            $uuid = serv_rep_dxm::getPb($acc['cookie']);
            if(!empty($uuid)){
                //查看同步是否完成
                serv_rep_dxm::getPbEnd($acc['cookie'], $uuid);

                //获取PB进行中的列表
                $pbList = serv_rep_dxm::getPbList($acc['cookie']);
                if(!empty($pbList)) {
                    core_base::log(['account' => $acc['account'], 'pbList' => $pbList], 'editPb');
                    //电话通知有正在进行的广告，并尝试取消
                    foreach ($pbList as $id => $state){
                        serv_rep_dxm::editPb($acc['cookie'], $id);
                    }
//                    if(!empty($acc['phone'])){
//                        $phone = explode(',', $acc['phone']);
//                        foreach ($phone as $p) {
//                            $pRes = model_api_aliApi::phoneNotification($p, 'TTS_202806874', ['qty' => count($pbList)]); // TTS_202817785
//                            core_base::log(['account' => $acc['account'], 'phone' => $p, 'pRes' => $pRes], 'phoneNotification');
//                        }
//                    }
                }
            }
            core_base::log(['account' => $acc['account'], 'info' => '结束'], 'getYunPb');
        }
    }

    /**
     * 描述 : 同步产品信息
     * 作者 : Zoro.Zhu
     */
    public static function getDxmInfo(){
        $account = L::sql("SELECT
            account, cookie 
        FROM
            vs_account_cookie 
        WHERE
            1 ");
        foreach ($account as $acc) {
            $uuid = serv_rep_dxm::syncProduct($acc['cookie']);
            core_base::log(['account' => $acc['account'], 'uuid' => $uuid], 'getProductInfo');
            $uuid = serv_rep_dxm::syncOrder($acc['cookie']);
            core_base::log(['account' => $acc['account'], 'uuid' => $uuid], 'getOrderInfo');
        }
        echo 'ok';
    }

    /**
     * 描述 : 刷新登录授权cookie
     * 作者 : Zoro.Zhu
     */
    public static function updateCookie(){
        $res = serv_rapi_publish::getEbayItemInfo('372976891944');
//        p($res);
        $res = serv_rapi_publish::getSku('UUU239409');
//        p($res);
        $res = serv_rapi_publish::getPdmSkuInfo('HHH052568007');
//        p($res);
        for ($i = 0; $i < count(serv_rep_taomaiwang::$cookie); $i++){
            $res = serv_rep_taomaiwang::getItem('Lounger', 2, $i);
        }
        //刷新wish后台账号的cookie
        $accountData = L::sql("SELECT
            cookie, xToken, state, merchantId, `name`
        FROM
            `wish_seller_account` 
        WHERE
            1");
        if(!empty($accountData)){
            foreach($accountData as $row){
                $sql = "SELECT
                    a.id 
                FROM
                    `wish_product_stats` a
                    LEFT JOIN wish_product b ON a.id = b.id 
                WHERE
                    b.account = '{$row['name']}' 
                ORDER BY
                    a.date DESC 
                    LIMIT 1 ";
                $product = L::sql($sql);
                if(empty($product[0]['id'])){
                   continue;
                }
                $params = [
                    'cookie' => $row['cookie'],
                    'xToken' => $row['xToken'],
                    'merchantId' => $row['merchantId'],
                    'id' => $product[0]['id'],
                    'day' => 22,
                ];
                $res = serv_rep_wish::getProductStats($params);
                if($res === false){
                    echo $row['name'] . '->过期<br>';
                    L::sql("UPDATE `wish_seller_account` SET `state` = 2, `updDate` = " . date('Y-m-d H:i:s') . " WHERE `name` = '{$row['name']}'");
                }else{
                    echo $row['name'] . '->正常<br>';
                    L::sql("UPDATE `wish_seller_account` SET `state` = 1, `updDate` = " . date('Y-m-d H:i:s') . " WHERE `name` = '{$row['name']}'");
                }
            }
        }
        //刷新wish买家账号的授权信息
        $token = model_wishBuyAccount::getParamsInfo();
        foreach($token as $to){
            $data = $to + ['productId' => '604c390cf0972fc20ad4b78e'];
            //先浏览产品,并获取变种ID
            $variation = serv_rep_wish::getProductInfoNew($data);
        }
    }

    /**
     * 描述 : 重新交运抢单号
     * 作者 : Zoro.Zhu
     */
    public static function getTrack(){
        $account = L::sql("SELECT
            account, cookie 
        FROM
            vs_account_cookie 
        WHERE
            1 ");
        for ($i = 0; $i < 120; $i++){
            foreach ($account as $acc) {
                $res = serv_rep_dxm::getTrack($acc['cookie']);
                core_base::log(['account' => $acc['account'], 'res' => $res], 'getTrack');
            }
            sleep(1);
        }
        echo 'ok';
    }

    /**
     * 描述 : 定时发布一个待发布的产品
     * 作者 : Zoro.Zhu
     */
    public static function publishProduct(){
        set_time_limit(0);
        $account = L::sql("SELECT
            account, cookie 
        FROM
            vs_account_cookie 
        WHERE
            account LIKE 'zoro_zhu%' 
        OR account like 'xiaolin%'");
        $params['state'] = 0;
        $params['productState'] = 0;
        $params['inventoryLift'] = '';
        $params['inventoryRight'] = '';
        $params['pageSize'] = 50;
        foreach ($account as $acc){
            $aId = serv_rep_dxm::getAccountId($acc['cookie']);
            foreach($aId as $id){
                $params['shopId'] = $id;
                $product = serv_rep_dxm::getProduct($acc['cookie'], $params);
                //发布一个产品
                serv_rep_dxm::publishProduct($acc['cookie'],current($product));
            }
        }
        echo 'ok';
    }

    /**
     * 描述 : 获取产品信息
     * 作者 : Zoro.Zhu
     */
    public static function getProduct(){
        $info = L::sql("SELECT `name` FROM wish_seller_account WHERE state = 1");
        foreach ($info as $row){
            of_base_com_mq::set(['getProduct', $row['name']],['day' => 2, 'account' => $row['name']]);
        }
    }

    /**
     * 描述 : 添加获取产品统计信息的MQ
     * 作者 : Zoro.Zhu
     */
    public static function getProductStats(){
        $sql = "SELECT
            id, account 
        FROM
            `wish_product` 
        WHERE
            reviewStatus IN ('approved','pending')
        AND removedByMerchant = 0"; //numberSaves + numberSold > 0
        $limit = 0;
        while (true){
            $s = $sql . " LIMIT {$limit},10000";
            $limit += 10000;
            $product = L::sql($s);
            if(empty($product[0])){
                break;
            }
            $sqlInsert = "INSERT INTO `_of_com_mq`(`mark`, `vHost`, `queue`, `type`, `msgId`, `data`, `syncCount`, `updateTime`, `createTime`, `syncLevel`, `lockTime`, `lockMark`) VALUES";
            $date = date('Y-m-d H:i:s');
            foreach ($product as $row) {
                $json = addslashes(json_encode($row));
                $sqlInsert .= "('{$row['id']}', '', 'vs', 'getProductStats', '{$row['id']}', '{$json}', 0, '{$date}', '{$date}', 0, '{$date}', ''),";
            }
            L::sql(trim($sqlInsert, ',') . " ON DUPLICATE KEY UPDATE 
            `data` = VALUES(`data`)");
        }
    }

    /**
     * 描述 : 获取销售图表的数据
     * 作者 : Zoro.Zhu
     */
    public static function getWishFlow(){
        $accountData = L::sql("SELECT
            cookie, xToken, state, merchantId, `name`
        FROM
            `wish_seller_account` 
        WHERE
            state = 1");
        if(!empty($accountData)){
            foreach($accountData as $row){
                $params = [
                    'cookie' => $row['cookie'],
                    'xToken' => $row['xToken'],
                    'day' => 22,
                ];
                $res = serv_rep_wish::getFlow($params);
                if(!empty($res)){
                    $insertSql = "INSERT INTO `wish_flow`(`date`, `account`, `data`) VALUES ";
                    foreach($res as $r){
                        $date = date('Y-m-d', $r['x']);
                        $json = addslashes(json_encode($r));
                        $insertSql .= "('{$date}', '{$row['name']}', '{$json}'),";
                    }
                    L::sql(trim($insertSql, ',') . " ON DUPLICATE KEY UPDATE 
                    `data` = VALUES(`data`)");
                }
            }
        }
    }

    /**
     * 描述 : 获取店铺金额情况
     * 作者 : Zoro.Zhu
     */
    public static function getBalance(){
        $accountData = L::sql("SELECT
            cookie, xToken, state, merchantId, `name`
        FROM
            `wish_seller_account` 
        WHERE
            1");
        if(!empty($accountData)){
            foreach($accountData as $row){
                $params = [
                    'cookie' => $row['cookie'],
                    'xToken' => $row['xToken'],
                    'merchantId' => $row['merchantId'],
                ];
                $res = serv_rep_wish::nowBalanceList($params);
                if(!empty($res)){
                    $insertSql = "INSERT INTO `wish_balance`(`id`, `account`, `date`, `type`, `data`) VALUES";
                    foreach($res as $r){
                        $date = substr($r['date'], 0, -4);
                        $r['amount'] = round($r['amount']);
                        $json = addslashes(json_encode($r));
                        $id = md5($r['item_type'] . '::' . $r['date'] . '::' . $r['merchant_id'] . '::' . $r['amount'] . '::' . $r['order_id']);
                        $insertSql .= "('{$id}','{$row['name']}','{$date}', '{$r['item_type']}', '{$json}'),";
                    }
                    L::sql(trim($insertSql, ',') . " ON DUPLICATE KEY UPDATE 
                    `data` = VALUES(`data`)");
                }
            }
        }
    }

    /**
     * 描述 : 获取客服问题信息列表
     * 作者 : Zoro.Zhu
     */
    public static function getTicket(){
        $sql = "SELECT
            account, appKey, appSecret, accessToken, refreshToken, addName,`type`
        FROM
            `vs_account` 
        WHERE
            `type` = 'wish'
        AND `state` = 0";
        if($data = L::sql($sql)) {
            foreach ($data as $row) {
                $ticket = serv_rapi_wish::getTicket($row);
                if(!empty($ticket)){
                    p($row);
                    p($ticket);
                    exit;
                }
            }
        }
    }

    /**
     * 描述 : 登录wish，获取session
     * 作者 : Zoro.Zhu
     */
    public static function loginWish(){
        set_time_limit(0);
        $date = date('Y-m-d', time() - 86400);
        $accountData = L::sql("SELECT
            cookie, xToken, state, merchantId, `name`, username, `password`
        FROM
            `wish_seller_account` 
        WHERE (state = 2 or `cookie` NOT LIKE '%session=%' or updDate <= '{$date}')
        and username is not null
        and `password` is not null
        and username != ''
        and `password` != ''
        LIMIT 5");
        if(!empty($accountData)){
            foreach($accountData as $row){
                $cookies = explode(';', $row['cookie']);
                $bsid = $rd = '';
                foreach($cookies as $cookie){
                    $cookie = trim($cookie);
                    substr($cookie, 0, 3) == 'rd=' && $rd = substr($cookie, 3);
                    substr($cookie, 0, 5) == 'bsid=' && $bsid = substr($cookie, 5);
                }
                $params = [
                    'username' => $row['username'],
                    'password' => $row['password'],
                    'xToken' => $row['xToken'],
                    'bsid' => $bsid,
                    'rd' => $rd,
                ];
                if(!empty($params['rd'])){
                    $res = serv_rep_wish::login($params);
                    if(!empty($res)){
                        if(substr($res[0],0 ,5) == 'bsid='){
                            continue;
                        }
                        $new = '_xsrf=' . $params['xToken'] . '; bsid=' . $params['bsid'];
                        foreach($res as $re){
                            $new .= "; {$re}";
                        }
                        if(!strstr($new, 'rd=')){
                            $new .= ";rd=" . $rd;
                        }
                        L::sql("UPDATE `wish_seller_account` 
                        SET 
                            `cookie` = '{$new}',
                            `updDate` = '" . date('Y-m-d H:i:s') . "',
                            `state` = 1
                        WHERE
                            `name` = '{$row['name']}'");
                    }
                }
            }
        }
    }

    /**
     * 描述 : 自动调价
     * 作者 : Zoro.Zhu
     */
    public static function autoUpdatePrice(){
        set_time_limit(0);
        $date = date('Y-m-d H:i:s', time() - 86400);
        $sql = "SELECT
            configData 
        FROM
            `wish_product_update_price` 
        WHERE
            execTime <= '{$date}'";
        $info = L::sql($sql);
        foreach($info as $row){
            $config = json_decode($row['configData'], true);
            $token = model_vsAccount::getAccountToken(['account' => $config['account']]);
            $productData = serv_rapi_wish::getProductData(['id' => $config['id'], 'accessToken' => $token['accessToken']]);
            //计算新的运费及数据
            $fee = rand($config['min']['shippingFee'], $config['max']['shippingFee']);
            $a = $fee / $config['range']['shippingFee'];
            $a = round($a);
            $a *= $config['range']['shippingFee'];
            $newShipFee = $config['oldShipFee'] + $a;

            $feeData = [];
            foreach($productData['data']['Product']['country_shippings'] as $ps){
                $feeData['localized_' . $ps['CountryShipping']['country_code']] = $newShipFee;
            }
            //操作运费修改
            serv_rapi_wish::updateShipping(['id' => $config['id'], 'accessToken' => $token['accessToken'], 'fee' => $feeData]);

            //计算新的产品售价及数据
            $oldPriceInfo = json_decode(stripslashes($config['oldPriceInfo']), true);
            foreach($oldPriceInfo as $r){
                $sku = $r['Variant']['sku'];
                $fee = rand($config['min'][$sku], $config['max'][$sku]);
                $a = $fee / $config['range'][$sku];
                $a = round($a);
                $a *= $config['range'][$sku];
                $newPrice = $r['Variant']['localized_price'] + $a;
                $data = [
                    'localized_price' => $newPrice,
                    'localized_currency_code' => 'CNY',
                ];
                //执行修改
                serv_rapi_wish::updateSkuInfo(['sku' => $sku, 'access_token' => $token['accessToken']] + $data);
            }
            L::sql("UPDATE `wish_product_update_price` 
            SET `execTime` = '" . date('Y-m-d H:i:s') . "' 
            WHERE
                `id` = '{$config['id']}'");
        }
    }

    /**
     * 描述 : 获取PB广告
     * 作者 : Zoro.Zhu
     */
    public static function getPbList(){
        set_time_limit(0);
        $sql = "SELECT
            account, appKey, appSecret, accessToken, refreshToken, addName,`type`
        FROM
            `vs_account` 
        WHERE
            `type` = 'wish'
        AND `state` = 0";
        if($data = L::sql($sql)) {
            foreach ($data as $row) {
                $pbList = serv_rapi_wish::getPbList($row);
                if(empty($pbList['data'])){
                    continue;
                }
                $insertSql = "INSERT INTO `wish_pb`(`id`, `account`, `pbData`) VALUES ";
                foreach ($pbList['data'] as $pb){
                    $json = addslashes(json_encode($pb));
                    $insertSql .= " ('{$pb['id']}', '{$row['account']}', '{$json}'),";
                }
                $insertSql = trim($insertSql, ',');
                L::sql($insertSql . " ON DUPLICATE KEY UPDATE 
                    `pbData` = VALUES(`pbData`)");
            }
        }
    }

    /**
     * 描述 : 获取超级店长的关键词数据
     * 作者 : Zoro.Zhu
     */
    public static function getAllcjdcKeywodr(){
        set_time_limit(0);
        $i = 1;
        while (true) {
            $res = serv_rep_cjdc::getWishkw($i);
            $i++;
            if(empty($res)) {
               break;
            }
            $insertSql = "INSERT INTO `cjdc_keyword`(`keyword`, `data`) VALUES";
            foreach ($res as $row) {
                $json = addslashes(json_encode($row));
                $insertSql .= " ('{$row['keyword']}', '{$json}'),";
            }
            L::sql(trim($insertSql, ',') . " ON DUPLICATE KEY UPDATE 
                `data` = VALUES(`data`)");
        }
    }

}
return true;